package com.cskaoyan.uploadutil;

import com.cskaoyan.storagecreateproperties.CskaoyanProperties;
import com.cskaoyan.storagecreateproperties.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author jiaolei
 */

@EnableConfigurationProperties(CskaoyanProperties.class)
public class FileUploadBySpringUtils {
    public static String uploadFile(MultipartFile file, String fileType,String imgLocation){

//        String originalFilename = file.getOriginalFilename();
        //---------------------------------------
//        int hashCode = originalFilename.hashCode();
//        String hexString = Integer.toHexString(hashCode);
//        char[] chars = hexString.toCharArray();
//
//        String baseName=imgLocation+fileType;
//        for (char aChar : chars) {
//            baseName+="/"+aChar;
//        }
//        String realName=baseName+"/"+originalFilename;
//        File fileTo = new File(realName);
//        if(!fileTo.exists()){
//            fileTo.mkdirs();
//        }
//        try {
//            file.transferTo(fileTo);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        //返回图片的绝对路径
//        return realName;
        //-----------------------------------------
//        String absolutePath=imgLocation + originalFilename;
//        File file1 = new File(imgLocation);
//        try {
//            file.transferTo(file1);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return absolutePath;

        String originalFilename = file.getOriginalFilename();
        int hashCode = originalFilename.hashCode();
        String hexString = Integer.toHexString(hashCode);
        char[] chars = hexString.toCharArray();

        String baseName="E:/spring/"+fileType;
        for (char aChar : chars) {
            baseName+="/"+aChar;
        }
        String realName=baseName+"/"+originalFilename;
        File fileTo = new File(realName);
        if(!fileTo.exists()){
            fileTo.mkdirs();
        }
        try {
            file.transferTo(fileTo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return realName;
    }
}
